import {AlertController, Events, LoadingController, ModalController, NavController, ToastController} from '@ionic/angular';
import {Component, OnDestroy, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Storage} from '@ionic/storage';
import {HttpService} from '../../services/http.service';
import {LoginSuccess} from '../../actions/auth.actions';
import {select, Store} from '@ngrx/store';
import * as authReducer from '../../reducers/auth.reducer';
import {mobileValidator} from '../../common/validators';
import {ActivatedRoute} from '@angular/router';
import {UtilService} from '../../services/util.service';
import {AppConfig} from '../../common/app-config.enum';
import {KeyAndSign} from '../../common/key-and-sign.enum';
import {BasePage} from '../../common/basePage';
import {UrlAndOPT} from '../../common/url-and-opt.enum';

/**
 * 登录
 */
@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage extends BasePage implements OnInit, OnDestroy {

  formModel: FormGroup;
  pwdObj: any = {
    inputType: 'password',
    icon: 'md-eye-off',
    color: 'medium'
  };

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              private modalCtrl: ModalController,
              private alertCtrl: AlertController,
              private routeInfo: ActivatedRoute,
              private service$: HttpService,
              private utilService: UtilService,
              private storage: Storage,
              private fb: FormBuilder,
              private loadingCtrl: LoadingController,
              private store: Store<authReducer.AuthState>,
              private events: Events
  ) {
    super(navCtrl, toastCtrl);
    this.formModel = fb.group({
      mobile: [null, [Validators.required, mobileValidator]],
      password: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(20)]],
      userType: [1, [Validators.required]]
    });
    // 侦听登录状态变化
    this.store.pipe(select(authReducer.getAuth))
      .subscribe(authState => {
        if (authState.status === 0) {
          // 退出登录后，重置表单
          this.formModel.patchValue({
            mobile: null,
            password: '',
            userType: 1
          });
        }
      });
    // 注册成功或密码登录时，接收发送过来的mobile
    this.events.subscribe(AppConfig.TOPIC_MOBILE, data => {
      this.formModel.get('mobile').setValue(data['mobile'] * 1);
      this.formModel.get('password').setValue('');
    });
  }

  ngOnInit() {
  }

  ngOnDestroy(): void {
    this.events.unsubscribe(AppConfig.TOPIC_MOBILE);
  }

  // 执行登录
  async doLogin() {
    if (this.formModel.valid) {
      const loading = await this.loadingCtrl.create({
        message: '登录中'
      });
      await loading.present();
      // 对password加密
      const password = this.utilService.encryptByDES(this.formModel.value['password'], KeyAndSign.DES_KEY);
      // 登录所需参数：mobile password deviceType userType
      const obj = await this.service$.doRequest(UrlAndOPT.auth_login, {...this.formModel.value, password: password}).toPromise();
      await loading.dismiss();
      if (obj && obj[AppConfig.USER_INFO_KEY]) {
        const userInfo = {
          [AppConfig.USER_INFO_KEY]: obj[AppConfig.USER_INFO_KEY],
          userRole: obj['userRole'],
          userType: obj['userType'],
          mobile: this.formModel.value['mobile'],
          password: password
        };
        await this.storage.set(AppConfig.USER_INFO, userInfo);
        this.store.dispatch(new LoginSuccess({status: 1, userInfo: userInfo}));
        this.events.publish(AppConfig.TOPIC_USER_FUNC); // 登录成功后，刷新我的页面(防止切换用户后信息不自动刷新的问题)
        // 检测用户迁移状态
        await this.service$.getUserStatus();
      }
    }
  }

  // 切换显示密码
  showPassword() {
    const isText = this.pwdObj.inputType === 'text';
    this.pwdObj = {
      inputType: isText ? 'password' : 'text',
      icon: isText ? 'md-eye-off' : 'md-eye',
      color: isText ? 'medium' : 'tertiary'
    };
  }

}
